//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/.
// 

#include "IP.h"
#include "app_pck_m.h"
#include "ip_pck_m.h"
#include "eth_pck_m.h"

Define_Module(IP);

void IP::initialize(){
	mySuffix=par("suffix");
	myIP<<"172.168.32."<<mySuffix;
	index=0;
}

void IP::handleMessage(cMessage *msg){
	//check if packet came from application layer
	if (dynamic_cast<App_pck *>(msg)){
		//if the channel was busy
		App_pck *app_packet= (App_pck*)msg;
		//creates a new IP packet
		IP_pck *ip_packet= generatePacket();
		//generate destination address
		setDestinationAddress(ip_packet);
		ip_packet->encapsulate(app_packet);
		//send packet to ethernet gate
		send(ip_packet, "toEthernet");
	}
	//message is from ethernet module
	else if(dynamic_cast<IP_pck *>(msg)){
		IP_pck* ip_packet= (IP_pck*)msg;
		if (strcmp(ip_packet->getDestAddress(), myIP.str().c_str())==0){
			cPacket *app_packet= ip_packet->decapsulate();
			send(app_packet,"toApp");
		}
		else
			drop(msg);
	}
	else
		drop(msg);
}

IP_pck* IP::generatePacket(){
	IP_pck *ip_pck= new IP_pck ("ip_packet");
	//set header length to 20 bytes
	ip_pck->setByteLength(20);
	//set source IP address
	ip_pck->setSourceAddress(myIP.str().c_str());

	return ip_pck;
}

void IP::setDestinationAddress(IP_pck *pck){
	//generate random suffix index
	do{
		index= par("randomIP");
		index+=1;
	} while (index==mySuffix);
	string dIP ("172.168.32.0");
	ostringstream hostSuffix;
	hostSuffix<<index;
	dIP.replace(11, 1, hostSuffix.str().c_str());
	pck->setDestAddress(dIP.c_str());
}


